﻿using System;
using System.Data.Entity.Infrastructure;
using System.Web;

namespace SnippetBox.Core.Data.Context {
    public static class ContextHelper<T> where T : class, IObjectContextAdapter, new() {

        private const string OBJECT_CONTEXT_KEY = "ObjectContext";

        public static T GetCurrentContext() {
            HttpContext httpContext = HttpContext.Current;

            if (httpContext != null) {
                string contextTypeKey = OBJECT_CONTEXT_KEY + typeof(T).Name;

                if (httpContext.Items[contextTypeKey] == null) {
                    httpContext.Items.Add(contextTypeKey, new T());
                }
                return httpContext.Items[contextTypeKey] as T;
            }

            throw new ApplicationException("There is no HttpContext available.");
        }
    }
}
